<template>
  <div class="online-sale">
    <div class="naviga">数据采集&nbsp;>&nbsp;线下销售数据</div>
    <div class="border-r margin-top">
      <div class="title">
        终端销售数据
        <span class="pull-right">更新时间： {{today}}</span>
      </div>
      <el-col :span="24" style="padding: 15px">
        <div class="left-date">
          <el-tag type="info" :key="tag" v-for="tag in checkedCities" style="margin-right: 5px;margin-bottom: 5px" closable
                  :disable-transitions="false"
                  @close="handleClose(tag)">{{tag}}</el-tag>
        </div>
        <el-button type="primary" class="pull-right" @click="setTime">设置查看时间段</el-button>
      </el-col>
      <el-col :span="24" style="padding: 15px">
        <div class="tag tag1">
          <div class="tag-sum">{{amountCount}}</div>
          <div class="tag-title">总销售额（元）</div>
        </div>
        <div class="tag tag2">
          <div class="tag-sum">{{salesCount}}</div>
          <div class="tag-title">总销售（件）</div>
        </div>
        <el-upload
          style="display:inline-block;vertical-align: middle;height: 32px"
          class="upload-demo"
          action="/front/excelUpload?method=DataAc_API4030"
          name="file"
          :data="uploadConfig"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          accept=".xlsx">
          <el-button size="small" type="primary">上传数据</el-button>
        </el-upload>
        <a class="el-button el-button--primary el-button--small" href="/file/download?fileName=线下销售数据模板.xlsx" download="线下销售数据模板" >下载模板</a>
      </el-col>
      <el-table
        :data="tableData"
        @sort-change='changeSort'
        border
        style="width: 100%;margin-top: 15px">
        <el-table-column
          label="数据时间段（月）"
          prop="dateTime"
          sortable="custom"
          width="200">
        </el-table-column>
        <el-table-column
          label="数据主题"
          prop="dataTheme">
        </el-table-column>
        <el-table-column
          label="全渠道销额"
          width="140"
          sortable="custom"
          prop="amountCount">
        </el-table-column>
        <el-table-column
          label="全渠道销量"
          sortable="custom"
          prop="salesCount"
          width="140">
        </el-table-column>
        <el-table-column
          label="数据更新时间"
          prop="dataTime"
          width="200">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button @click="deleteData(scope.row.dateTime)" type="text" size="small">删除</el-button>
            <el-button type="text" size="small" @click="editData(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="showDetail(scope.row)">详细数据</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding: 20px"
        background
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!--设置时间段-->
    <div class="modal fade" id="setting">
      <div class="modal-dialog modal-dialog-big" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div class="naviga">设置查看时间段</div>
          </div>
          <div class="modal-body">
            <div class="text-center">
              <el-tag>最多可以选择12个月的数据，目前已选择{{checkedCities.length}}个</el-tag>
            </div>
            <div class="row margin-top" style="margin-left: 15px;margin-right: 15px">
              <el-col :span="24">
                <el-checkbox-group v-model="checkedCities" :max="12">
                  <el-checkbox v-for="city in cities" :label="city" :key="city" style="margin-left: 30px">{{city}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </div>
          </div>
          <div class="modal-footer">
            <div class="text-center">
              <el-button type="primary" @click="changeData">确认</el-button>
              <button type="button" class="el-button el-button--info" data-dismiss="modal">取消</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--编辑数据-->
    <div class="modal fade" id="editData">
      <div class="modal-dialog modal-dialog-big" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div class="naviga">编辑数据</div>
          </div>
          <div class="modal-body">
            <div class="row" style="margin-left: 15px;margin-right: 15px">
              <el-col :span="24">
                <el-form :model="ruleForm2" :rules="rules" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="数据时间" prop="dateTime">
                    <el-select v-model="ruleForm2.dateTime" placeholder="请选择时间">
                      <el-option v-for="items in cities" :label="items" :value="items"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="主题" prop="dataTheme">
                    <el-input v-model="ruleForm2.dataTheme"></el-input>
                  </el-form-item>
                </el-form>
              </el-col>
            </div>
          </div>
          <div class="modal-footer">
            <div class="text-center">
              <el-button type="primary" @click="submitForm2('ruleForm2')">确认</el-button>
              <button type="button" class="el-button el-button--info" data-dismiss="modal">取消</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--详细数据-->
    <div class="modal fade" id="detail">
      <div class="modal-dialog modal-dialog-big" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div class="naviga">数据采集&nbsp;>&nbsp;线下销售数据&nbsp;>&nbsp;详细数据</div>
          </div>
          <div class="modal-body">
            <div class="row" style="margin-left: 15px;margin-right: 15px">
              <div class="border-r margin-top">
                <div class="title">
                  {{formInline.dateTime}}+{{row.dataTheme}}
                </div>
                <div class="row" style="margin-left: 10px;margin-right: 10px">
                  <el-col :span="24" style="padding: 15px">
                    <div class="tag tag3">
                      <div class="tag-sum">{{row.amountCount}}</div>
                      <div class="tag-title">总销售额（元）</div>
                    </div>
                    <div class="tag tag4">
                      <div class="tag-sum">{{row.salesCount}}</div>
                      <div class="tag-title">总销售（件）</div>
                    </div>
                  </el-col>
                </div>
              </div>
              <div class="border-r margin-top" style="padding: 15px;overflow: hidden">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                  <el-form-item label="品类">
                    <el-select v-model="formInline.categoryName" placeholder="品类" @change="brandList()">
                      <el-option label="全部" value="ALL"></el-option>
                      <el-option
                        v-for="item in categoryOptions"
                        :key="item.id"
                        :label="item.categoryName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="品牌">
                    <el-select v-model="formInline.brandName" placeholder="品牌" @change="modelList()">
                      <el-option label="全部" value="ALL"></el-option>
                      <el-option
                        v-for="item in brandOptions"
                        :key="item.brandId"
                        :label="item.brandName"
                        :value="item.brandId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="型号">
                    <el-select v-model="formInline.productCode" placeholder="型号">
                      <el-option label="全部" value="ALL"></el-option>
                      <el-option
                        v-for="item in modelOptions"
                        :key="item.productCode"
                        :label="item.productCode"
                        :value="item.productCode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="省份">
                    <el-select v-model="formInline.province" placeholder="省份" @change="cityList">
                      <el-option label="全部" value="ALL"></el-option>
                      <el-option
                        v-for="item in proOptions"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="市区">
                    <el-select v-model="formInline.city" placeholder="市区">
                      <el-option label="全部" value="ALL"></el-option>
                      <el-option
                        v-for="item in cityOptions"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="渠道">
                    <el-select v-model="formInline.channelId" placeholder="渠道" @change="shopList">
                      <el-option label="全部" value="0"></el-option>
                      <el-option
                        v-for="item in channelOptions"
                        :key="item.channelId"
                        :label="item.channelName"
                        :value="item.channelId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="店铺/终端">
                    <el-select v-model="formInline.shopId" placeholder="店铺/终端">
                      <el-option label="全部" value="0"></el-option>
                      <el-option
                        v-for="item in shopOptions"
                        :key="item.shopId"
                        :label="item.shopName"
                        :value="item.shopId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" class="pull-right" @click="reset" >清空并选择全部</el-button>
                    <el-button type="primary" class="pull-right search" @click="currentPage = 1;search()" >查询</el-button>
                  </el-form-item>
                </el-form>
                <el-table
                  :data="detailTable"
                  border
                  style="width: 100%;margin-top: 15px">
                  <el-table-column
                    label="品类"
                    prop="categoryName"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="产品型号"
                    prop="productCode"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="产品属性"
                    prop="productAttribute"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="零售价"
                    prop="retailPrice"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="地区"
                    width="200">
                    <template slot-scope="scope">
                      {{scope.row.province }}-{{scope.row.city}}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="渠道名称"
                    prop="channelName"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="店铺/终端名称"
                    prop="shopName">
                  </el-table-column>
                  <el-table-column
                    label="店铺/终端零售价"
                    prop="shopRetailPrice"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="销量"
                    prop="salesCount"
                    width="110">
                  </el-table-column>
                  <el-table-column
                    label="销额"
                    prop="amountCount"
                    width="110">
                  </el-table-column>
                </el-table>
                <el-pagination
                  style="float: right;margin-top: 10px"
                  layout="prev, pager, next"
                  :total="total1"
                  :current-page="currentPage1"
                  @current-change="pageChange">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
  </div>
  </div>
</template>
<style lang="less" scoped>
  .blue {
    color: #03a9f3;
  }
  .title {
    height: 50px;
    line-height: 50px;
    padding: 0 10px;
    border-bottom: 1px solid #efefef;
  }
  .left-date{
    display: inline-block;
    width: calc(100% - 200px);
  }
  .tag{
    width: 160px;
    height: 100px;
    display: inline-block;
    border-radius: 5px;
    margin-right: 15px;
  }
  .tag1{
    background:linear-gradient(to right,#FD8799, #F4E45D);
  }
  .tag2{
    background: linear-gradient(to right,#50D38B, #3ECCE0);
  }
  .tag3{
    background: linear-gradient(to right,#A1D3F2, #65BDF5);
  }
  .tag4{
    background: linear-gradient(to right,#65BDF5, #9B97E7);
  }
  .tag-sum{
    color: white;
    font-weight: 800;
    font-size: 18px;
    line-height: 50px;
    width: 100%;
    text-align: center;
  }
  .tag-title{
    color: white;
    font-size: 15px;
    line-height: 50px;
    width: 100%;
    text-align: center;
  }
  .product-content {
    height: 60px;
    line-height: 20px;
    font-size: 14px;
    box-sizing: border-box;
    padding: 20px;
  }
  .modal-dialog-big{
    width: 100%;
    margin-top: 0;
    border-radius: 0;
  }
  .modal-body{
    background-color: #F6F6F6;
    padding-left: 0;
    padding-right: 0;
  }
  .left-td{
    width: 95px;
    text-align: right;
    padding-right: 10px;
  }
  .search {
    margin-right: 20px;
  }
</style>
<script type="es6">
  export default {
    data() {
      return {
        commentNum:0,
        today: `1970-01-01 08:00:00`,
        //表格列表
        tableData: [],
        total: 0,
        pSize: 10,
        currentPage: 1,
        total1: 0,
        currentPage1: 1,
        checkedCities: [],
        cities: [],
        // 总额销售量
        amountCount:0,
        salesCount:0,
        // 数据列表查询参数
        dateTime:'',
        tableName:'',
        order:'DESC',
        // 新增数据表单
        ruleForm: {
          dateTime: '',
          dataTheme: '',
        },
        rules: {
          dateTime: [
            { required: true, message: '请选择时间', trigger: 'blur' }
          ] ,
          dataTheme: [
            { required: true, message: '请输入主题', trigger: 'blur' }
          ]
        },
        // 编辑数据表单
        ruleForm2: {
          dateTime: '',
          dataTheme: '',
        },
        // 查看详情表单数据
        formInline:{
          dateTime:'',
          categoryName:'ALL',
          brandName:'ALL',
          productCode:'ALL',
          province:'ALL',
          city:'ALL',
          channelId:'',
          shopId:''
        },
        row:{},
        date:  [],
        //品类
        categoryOptions: [],
        // 品牌
        brandOptions:[],
        //产品型号
        modelOptions:[],
        // 省份
        proOptions:[],
        // 市
        cityOptions:[],
        // 渠道
        channelOptions:[],
        // 店铺
        shopOptions:[],
        // 数据详情分页
        pageNo2:1,
        // 详细情况表格
        detailTable:[],
        uploadConfig: {
          type: 'Document'
        },
      }
    },
    computed: {
      headers: function() {
        let token = sessionStorage.getItem("tokenName")
        return ({
          dipsToken: token,
        })
      }
    },
    mounted(){
      this.last_year_month()
      this.dataList()
      this.amountSale()
      this.categoryList()
      this.proList()
      this.channelList()
    },
    methods: {
      //页数
      handleSizeChange(val) {
        this.pSize = val;
        this.dataList();
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.dataList();
      },
      // 格式化日期
      tranTime(val){
        if(val < 10){
          return `0${val}`
        }else{
          return `${val}`
        }
      },
      // 获取当前最近24个月的数据
      last_year_month(){
        var d = new Date();
        var result = [];
        for(var i = 0; i < 24; i++) {
          d.setMonth(d.getMonth() - 1);
          var m = d.getMonth() + 1;
          m = m < 10 ? "0" + m : m;
          //在这里可以自定义输出的日期格式
					result.push(d.getFullYear() + "-" + m);
        }
        this.cities=result;
        // 设置默认选中时间段
        this.checkedCities.push(this.cities[0])
        this.changeData()
      },
      // 当前选取数据修改时，修改对应的数据列表
      changeData(){
        this.dateTime='';
        for(var i in this.checkedCities){
          this.dateTime=this.dateTime + this.checkedCities[i]+','
        }
        this.dataList();
        this.amountSale();
        $('#setting').modal('hide')
      },
      // 设置时间段
      setTime(){
        $('#setting').modal('show')
      },
      // 修改表格排序条件并且重新获取数据
      changeSort(prop){
        this.tableName=prop.prop;
        if(prop.order==="ascending"){
          this.order='ASC';
        }else {
          this.order='DESC';
        }
        // 重置页数后重新排序
        this.currentPage=1;
        this.dataList()
      },
      //1. 线下销售数据列表
      dataList(){
        this.$http.post(this.GLOBAL.host,{
          method:'DataAc_API4010',
          query:{
            dateTime:this.dateTime,
            tableName:this.tableName,
            order: this.order,
            pageNo:this.currentPage,
            pageSize:this.pSize
          }
        })
          .then((res) => {
            this.tableData=res.data.data.list;
            this.total=res.data.data.total
            var nowdate=new Date()
            this.today= `${nowdate.getFullYear()}-${this.tranTime(nowdate.getMonth()+1)}-${this.tranTime(nowdate.getDate())} ${nowdate.getHours()}:${this.tranTime(nowdate.getMinutes())}:${this.tranTime(nowdate.getSeconds())}`;
          })
          .catch((error) => {});
      },
      //2. 总额销售量
      amountSale(){
        this.$http.post(this.GLOBAL.host,{
          method:'DataAc_API4020',
          query:{
            dateTime:this.dateTime
          }
        })
          .then((res) => {
            this.amountCount=res.data.data.amountCount
            this.salesCount=res.data.data.salesCount
          })
          .catch((error) => {
            this.amountCount=0;
            this.salesCount=0
          });
      },
      // 新增数据表单验证
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addData()
          } else {
            return false;
          }
        });
      },
      //4 删除数据
      deleteData(dateTime){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post(this.GLOBAL.host,{
            method:'DataAc_API4060',
            query:{dateTime:dateTime}
          })
            .then((res) => {
              if(res.data.code=='200'){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.dataList();
                this.amountSale()
              }else{
                this.$message.error('删除失败');
              }
            })
            .catch((error) => {this.$message.error('删除失败');});
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 编辑数据
      editData(data){
        this.ruleForm2.dateTime=data.dateTime
        this.ruleForm2.dataTheme=data.dataTheme
        $('#editData').modal('show')
      },
      // 编辑数据表单验证
      submitForm2(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.saveData()
          } else {
            return false;
          }
        });
      },
      // 5编辑后保存
      saveData(){
        $('#editData').modal('hide')
        this.$http.post(this.GLOBAL.host,{
          method:'DataAc_API4070',
          query:this.ruleForm2
        })
          .then((res) => {
            if(res.data.code=='200'){
              this.$message({
                message: '保存数据成功',
                type: 'success'
              });
              this.dataList();
              this.amountSale()
            }else{
              this.$message.error('保存数据失败');
            }
          })
          .catch((error) => {this.$message.error('保存数据失败');});
      },
      // 显示详细数据
      showDetail(row){
        $('#detail').modal('show');
        this.row=row
        this.formInline.dateTime=row.dateTime;
        this.$http.post(this.GLOBAL.host,{
          method:'DataAc_API4020',
          query:{
            dateTime:this.formInline.dateTime
          }
        })
          .then((res) => {
            this.row.amountCount=res.data.data.amountCount
            this.row.salesCount=res.data.data.salesCount
          })
          .catch((error) => {});
        this.detailList()
      },
      // 6：获取品类下拉框
      categoryList(){
        this.$http.post(this.GLOBAL.host,{
          method:'getSubCategory'
        })
          .then((res) => {
            this.categoryOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 7：根据品类获得品牌列表
      brandList(){
        this.formInline.brandName = 'ALL'
        this.formInline.productCode = 'ALL'
        this.$http.post(this.GLOBAL.host,{
          method:'getCBRelation',
          "query":{
            "categoryId": this.formInline.categoryName
          }
        })
          .then((res) => {
            this.brandOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 8：根据品类品牌获取型号列表
      modelList(){
        this.formInline.productCode = 'ALL'
        this.$http.post(this.GLOBAL.host,{
          method:'getProduct',
          query:{
            categoryId: this.formInline.categoryName,
            brandId:this.formInline.brandName
          }
        })
          .then((res) => {
            this.modelOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 9获取省市接口
      proList(){
        console.log(this.formInline)
        this.$http.post(this.GLOBAL.host,{
          method:'getOnlineSalesProvince'
        })
          .then((res) => {
            this.proOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 10获取市接口
      cityList(){
        this.formInline.city = 'ALL'
        this.$http.post(this.GLOBAL.host,{
          method:'getOnlineSalesCity',
          "query":{
            "province":this.formInline.province
          }
        })
          .then((res) => {
            this.cityOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 11：获取渠道列表
      channelList(){
        this.$http.post(this.GLOBAL.host,{
          "method":"DataAc_API4081",
          "query":{
            "channelType":"线下"
          }
        })
          .then((res) => {
            this.channelOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 12:根据省市和渠道获取到店铺列表
      shopList(){
        console.log(this.formInline)
        this.$http.post(this.GLOBAL.host,{
          "method":"getOnlineSalesShop",
          "query":{
            "channelId": this.formInline.channelId,
            "province": this.formInline.province,
            "city": this.formInline.city
          }
        })
          .then((res) => {
            this.shopOptions=res.data.data
          })
          .catch((error) => {});
      },
      // 13:获取到线下销售详情
      detailList(){
        this.$http.post(this.GLOBAL.host,{
          "method":"DataAc_API4080",
          "query":{
            "dateTime":this.formInline.dateTime,
            "categoryName": this.formInline.categoryName,
            "brandName": this.formInline.brandName,
            "productCode":this.formInline.productCode,
            "province":this.formInline.province,
            "city":this.formInline.city,
            "channelId":this.formInline.channelId,
            "shopId":this.formInline.shop,
            "pageNo":this.pageNo2,
            "pageSize":10
        }
        })
          .then((res) => {
            this.detailTable=res.data.data.list
            this.total1 = res.data.data.total
          })
          .catch((error) => {});
      },
      reset(){
          this.formInline.categoryName='ALL';
          this.formInline.brandName='ALL';
          this.formInline.productCode='ALL';
          this.formInline.province='ALL';
          this.formInline.city='ALL';
          this.formInline.channelId='0';
          this.formInline.shopId='0'
      },
      pageChange(pageNum) {
        this.currentPage1 = pageNum;
        this.search(pageNum)
      },
      search(pageNum) {
        const selectedCategory = _.find(this.categoryOptions, item => item.id === this.formInline.categoryName)
        const selectedBrand = _.find(this.brandOptions, item => item.brandId === this.formInline.brandName)
        this.$http.post(this.GLOBAL.host,{
          "method":"DataAc_API4080",
          "query":{
            "dateTime":this.formInline.dateTime,
            "categoryName": selectedCategory ? selectedCategory.categoryName : 'ALL',
            "brandName": selectedBrand ? selectedBrand.brandName : 'ALL',
            "productCode":this.formInline.productCode,
            "province":this.formInline.province,
            "city":this.formInline.city,
            "channelId":this.formInline.channelId,
            "shopId":this.formInline.shop,
            pageNo: pageNum || 1,
            pageSize: 10,
          }
        })
          .then((res) => {
            this.detailTable=res.data.data.list
            this.total1 = res.data.data.total
            this.currentPage1 = pageNum;
          })
          .catch((error) => {});
      },
      handleClose(tag) {
        console.log(tag)
        console.log(this.checkedCities.indexOf(tag))
        this.checkedCities.splice(this.checkedCities.indexOf(tag), 1);
        this.changeData()
      },
      // 导入数据
      handleAvatarSuccess(res) {
        if(res.code=='200'){
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success'
          });
          this.dataList()
        }else{
          this.$notify({
            title: '失败',
            message: '上传失败',
            type: 'error'
          });
        }
      }
    }
  };
</script>
